<?php

namespace App\Http\Controllers\admin\Slideshow_mangement;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\updateLoopCheck;

use App\Loop;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Storage;
use DB;

class UpdateLoopController extends Controller
{ 

	//得到所有轮播图的数据
    public function getAllLoop()
    {
    	$data=Loop::select('id','title as loop_title','img_path','post_title as article_title','post_id as article_id')->get()->toArray();
    	return response()->json(['code'=>200,'msg'=>'成功','data'=>$data]);
    }

    

    //查找文章
    public function searchArticle(Request $request)
    {
    	$article_title=$request->input('article_title');
        /*$articles=Post::select('id as article_id','title as article_title','user_name as author')
            ->where('title',$article_title)->orWhere('title','like','%'.$article_title.'%')->paginate(5);*/
        $data=DB::table('Posts as P')->join('users as u','P.user_id','u.id')
            ->select('P.id as article_id','title as article_title','user_name as author')
            ->Where('title','like','%'.$article_title.'%')->paginate(5);
    	return response()->json(['code'=>200,'msg'=>'成功','data'=>$data]);
    }
    //上传图片
    public function UpImage(Request $request)
    {

        $img=$request->file('picture');
        $allow_extend=['jpeg','jpg','png'];

        if($img->isValid())
        {
            $extend = $img->getClientOriginalExtension();
            if (!in_array($extend, $allow_extend)) {
                return response()->json(['code' => 100, 'msg' => '图片格式只能为jpeg,jpg,png']);
            }
            $img_name = md5(time()) . '.' . $extend;
            $result = Storage::disk('admin')->put($img_name, file_get_contents($img->getRealPath()));
            $img_path="storage/admin/".$img_name;
            return response()->json(['code' => 200, 'msg' => '成功', 'data' => $img_path]);
        }
    }

    //修改轮播图数据并保存
    public function updateLoop(updateLoopCheck $request)
    {

        $id=$request->id;
        if(!isset($request->img_path)){//未上传新图片
        $loop=Loop::find($id);
        $loop->title=$request->loop_title;
        $loop->post_title=$request->article_title;
        $loop->post_id=$request->article_id;
        $loop->save();
        return response()->json(['code'=>200,'msg'=>'成功']);
    }
    else{//上传新图片
        $loop=Loop::find($id);
        $loop->title=$request->loop_title;
        $loop->img_path=$request->img_path;
        $loop->post_title=$request->article_title;
        $loop->post_id=$request->article_id;
        $loop->save();
        return response()->json(['code'=>200,'msg'=>'成功']);
        }
    }


}

    

